from rest_framework import serializers
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import send_sms_code
from . import constants
import random


class SMSCodeSerializer(serializers.Serializer):
    """短信验证码视图序列化器"""
    image_code_id = serializers.UUIDField(label="UUID", write_only=True)
    text = serializers.CharField(label="图形验证码",max_length=4, min_length=4, write_only=True)

    def validate(self, attrs):
        mobile = self.context["view"].kwargs["mobile"]
        image_code_id = attrs["image_code_id"]
        text = attrs["text"]

        # 读取图片验证码,进行校验
        redis_conn = get_redis_connection("verify_codes")
        real_text = redis_conn.get("image_%s" % image_code_id)
        if not real_text:
            raise serializers.ValidationError("无效的图形验证码")
        redis_conn.delete("image_%s" % image_code_id)

        if real_text.decode().lower() != text.lower():
            raise serializers.ValidationError("图片验证码错误")

        # 生成手机验证码,保存到redis
        mobile_flag = redis_conn.get("mobile_flag_%s" % mobile)
        if mobile_flag:
            raise serializers.ValidationError("操作过于频繁")

        sms_code = "%06d" % random.randint(0, 999999)
        redis_conn.setex("sms_code_%s" % mobile, constants.SMS_CODE_EXPIRES, sms_code)
        redis_conn.setex("mobile_flag_%s" % mobile, constants.SEND_MESSAGE_TIME, 1)

        # 发送短信
        message_expires = int(sms_code) // 60
        # CCP().send_template_sms(mobile, [sms_code, message_expires], constants.MESSAGE_MODEL)
        send_sms_code.delay(mobile, sms_code, message_expires, constants.MESSAGE_MODEL)

        return attrs



